package com.xiaowei.gym.gymjsp.ware.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.xiaowei.gym.gymjsp.ware.service.ImportService;
import java.util.ArrayList;
import java.util.List;
public class ExcelImportListener<T,V> implements ReadListener<T>{
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<T> cachedDataList = new ArrayList<>();
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private ImportService<T,V> demoService;

    public ExcelImportListener(ImportService<T,V> tService) {
        this.demoService = tService;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        System.out.println("解析到一条数据信息:"+JSON.toJSONString(t));
        cachedDataList.add(t);
        if (cachedDataList.size() >= BATCH_COUNT){
            saveData();
            cachedDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        System.out.println("所有数据解析完成！");
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        System.out.println(cachedDataList.size()+"条数据，开始存储数据库！");
        //判断是否为空，为空就不存储，不为空就存储
        if (cachedDataList.size() == 0 || cachedDataList.isEmpty()){
            return;
        }else {
            demoService.batchInsert(cachedDataList);
            System.out.println("存储数据库成功！");
        }
    }
}
